import React, { useEffect, useMemo, useState } from 'react'
import '../../scss/ljc.scss'
import { Form, Input, Table, Space, Switch, Breadcrumb, Modal, Select, message, Upload} from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons'
import { List } from '../../axiosAPI/ljc';
import { useNavigate } from 'react-router-dom';
export default function User() {
    let Navigate = useNavigate()
    let [list, setList] = useState([])
    let [academy, setAcademy] = useState([])
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [componentSize, setComponentSize] = useState('default');
    let [adminId, setAdminId] = useState('')
    const [messageApi, contextHolder] = message.useMessage();

    //搜索数据
    let [searchName, setSearchName] = useState('')
    let [searchAcademy, setSearchAcademy] = useState('')
    let [searchRole, setSearchRole] = useState('')
    //修改数据
    let [updateName, setUpdateName] = useState('')
    let [updatePhone, setUpdatePhone] = useState('')
    let [updateAcademy, setUpdateAcademy] = useState('')
    let [updateRole, setUpdateRole] = useState('')

    //获取admin
    let getList = async () => {
        let { data: { data } } = await List(
            {
                url: '/ljc/adminList',

            }
        )
        setList(data)
    }
   console.log(list,'11111111111111111111111111111111111111111111111111111111');
   
    //搜索
    let getList1 = async () => {
        let { data: { data } } = await List(
            {
                method: 'post',
                url: '/ljc/adminList1',
                data: {
                    searchName,
                    searchAcademy,
                    searchRole
                }
            }
        )
        setList(data)
    }

    console.log(searchName,searchAcademy,searchRole);
    

    //获取学院表
    let getAcademy = async () => {
        let { data: { data } } = await List({
            url: '/ljc/academyList',
        })
        setAcademy(data)
    }
    useEffect(() => {
        getList()
        getAcademy()
    }, [])
    let newlist = useMemo(() => {
        let arr = []
        list.forEach(item => {
            arr.push({ ...item, key: item._id })
        })
        return arr
    })
    const onChange = async (e, id) => {
        // console.log(`switch to ${e}`,id);
        let obj = {
            status: e,
            id: id
        }

        let { data: { code } } = await List({
            method: 'post',
            url: '/ljc/changeStatus',
            data: obj
        })
        if (code === 200) {
            getList()
        }
    };
    const columns = [
        {
            title: '姓名',
            dataIndex: 'truename',
            key: 'truename',
            // render: (text) => <a>{text}</a>,
        },
        {
            title: '用户名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '学院',
            dataIndex: 'academy',
            key: 'academy',
            render: (_, record) => (
                <Space size="middle">
                    {
                        academy.filter(item => item._id == record?.academy._id).map(item => (
                            <span key={item._id}>{item.name}</span>
                        ))
                    }
                </Space>
            ),  
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            key: 'role',
        },
        {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
        },
        {
            title: '是否启用',
            dataIndex: 'status',
            key: 'status',
            render: (_, record) => (
                <Switch defaultChecked={record.status} onChange={(e) => { onChange(e, record._id) }} />
            ),
        },
        {
            title: '操作',
            dataIndex: '_id',
            key: '_id',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => { showModal(record._id) }
                    }>修改角色</a>
                </Space>
            ),
        },
    ];
    const showModal = (id) => {
        setIsModalOpen(true);
        setAdminId(id)
    };
    const handleOk = async () => {
        setIsModalOpen(false);
        let { data: { code } } = await List({
            method: 'post',
            url: '/ljc/updateAdmin',
            data: {
                adminId,
                updateName,
                updatePhone,
                updateAcademy,
                updateRole
            }
        })
        if (code === 200) {
            getList()
            setUpdateAcademy('')
            setUpdateName('')
            setUpdatePhone('')
            setUpdateRole('')
        }
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const onFormLayoutChange = ({ size }) => {
        setComponentSize(size);
    };

    //重置
    let reset = () => {
        setSearchName('')
        setSearchAcademy('')
        setSearchRole('')
    }
    //搜索
    let search = () => {
        getList1()
    }
    //导入
    const props = {
        name: 'file',
        action: 'http://localhost:3001/ljc/upload',
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info) {
            console.log();
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };
    //导出
    let exportFile = async () => {
        let { data: { code } } = await List({
            url: '/ljc/exportFile'
        })
        if (code === 200) {
            messageApi.open({
                type: 'success',
                content: '导出成功',
            });
        }
    }
    const items = [
        {
          label: <button>导入</button>,
          key: '0',
        },
        {
            label: <button>导出</button>,
            key: '1',
        }
    ]
    return (
        <div id='ljc'>
            {contextHolder}
            <div className="header">
                <Breadcrumb
                    style={{ marginLeft: '40px', marginTop: '10px' }}
                    items={[
                        {
                            title: '系统管理',
                        },
                        {
                            title: <a href="">用户管理</a>,
                        },
                    ]}
                />
                <h3><ArrowLeftOutlined onClick={() => { Navigate(-1) }} /><span>用户管理</span></h3>

            </div>
            <div className='body'>
                <div className='sou'>
                    <div>
                        <label>姓名:</label>
                        <input type='text' placeholder='请输入' value={searchName} onChange={(e) => { setSearchName(e.target.value) }}></input>
                    </div>
                    <div>
                        <label>学院:</label>
                        <select name="" value={searchAcademy} onChange={(e) => { setSearchAcademy(e.target.value) }}>
                            <option value='' checked>请选择</option>
                            {
                                academy.map(item => (
                                    <option key={item._id} value={item._id}>{item.name}</option>
                                ))
                            }
                        </select>
                    </div>
                    <div>

                        <label>角色:</label>
                        <select name="" value={searchRole} onChange={(e) => { setSearchRole(e.target.value) }}>
                            <option value='' checked>请选择</option>
                            <option value='超级管理员' checked>超级管理员</option>
                            <option value='讲师' checked>讲师</option>
                        </select>
                    </div>
                    <div>
                        <button onClick={search}>查询</button>
                        <button onClick={reset}>重置</button>
                        <Upload
                            name="file"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://localhost:3000/ljc/upload"
                            onChange={() => {
                                getList()
                                messageApi.open({
                                    type: 'success',
                                    content: 'This is a success message',
                                });
                            }}
                        >
                            <button >导入</button>
                        </Upload>
                        <button onClick={exportFile}>导出</button>
                    </div>
                </div>
                <div className="form">
                    <Table columns={columns} dataSource={newlist} />
                </div>
                <Modal title="修改角色" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                    <hr style={{ color: 'gray' }} />
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 14,
                        }}
                        layout="horizontal"
                        initialValues={{
                            size: componentSize,
                        }}
                        onValuesChange={onFormLayoutChange}
                        size={componentSize}
                        style={{
                            maxWidth: 600,
                            marginTop: '15px'
                        }}
                    >
                        <Form.Item label="姓名">
                            <Input type='text' placeholder='请选择' value={updateName} onChange={(e) => { setUpdateName(e.target.value) }} />
                        </Form.Item>
                        <Form.Item label="电话">
                            <Input type='text' placeholder='请选择' value={updatePhone} onChange={(e) => { setUpdatePhone(e.target.value) }} />
                        </Form.Item>
                        <Form.Item label="学院">
                            <Select placeholder='请选择' value={updateAcademy} onChange={(e) => { setUpdateAcademy(e) }}>
                                {
                                    academy.map(item => (
                                        <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item label="角色" >
                            <Select placeholder='请选择' value={updateRole} onChange={(e) => { setUpdateRole(e) }}>
                                <Select.Option value="超级管理员">超级管理员</Select.Option>
                                <Select.Option value="讲师">讲师</Select.Option>
                            </Select>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    )
}
